package cookie;

import utils.CookieUtils;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 返回指定Cookie给浏览器
 */
public class C3_ReadCookieByName extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("C3_ReadCookieByName被调用...");

        //得到指定的Cookie值
        //1.先得到浏览器携带的所有Cookie
        Cookie[] cookies = req.getCookies();

        //2.使用工具类获取指定的cookie
        Cookie email = CookieUtils.readCookieByName("email", cookies);
        if (null != email) {
            System.out.println("得到cookie name=" + email.getName() + " value=" + email.getValue());
        } else {
            System.out.println("没有找到cookie");
        }

        //3.给浏览器返回综合信息
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<h1>读取指定cookie成功</h1>");
        out.flush();
        out.close();
    }
}
